package com.spacing.app;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.codechimp.apprater.AppRater;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.senseilearning.anatomy.R;
import com.spacing.app.data.Chapter;
import com.spacing.app.data.Chapters;
import com.spacing.app.data.Section;
import com.spacing.app.data.Word;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;


public class SpacingAppActivity extends SherlockFragmentActivity {
	Chapters chapters = new Chapters();
	Chapter chapter = new Chapter();
	Section section = new Section();
	Word word = new Word();
	XmlPullParser xpp;
	SchemaHelper sh;
	String next[] = {};
	private GridView gridView;
	List<String[]> list = new ArrayList<String[]>();
	private ChapterAdapter adapter;
	ArrayList<String> test;
	TestFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		AppRater.app_launched(this);
		super.onCreate(savedInstanceState);
		SharedPreferences sp = getSharedPreferences("my_db", Context.MODE_PRIVATE);

		
		
		if (Build.VERSION.SDK_INT < 11) {
			// requestWindowFeature(Window.FEATURE_NO_TITLE);
		}

		ActionBar ab = getSupportActionBar();
		ab.setTitle(getString(R.string.title));

		//readCSV();
		//System.out.println(list.get(0)[0]);

		// sh = new SchemaHelper(this);
		readXML();
		/*
		 * long p = 0;
		 * 
		 * boolean hasVisited = sp.getBoolean("hasVisited", false); if
		 * (!hasVisited) { Editor e = sp.edit(); e.putBoolean("hasVisited",
		 * true); e.commit(); sh.beginTransaction(); for (int i = 0; i <
		 * chapters.size(); i++) { for (int j = 0; j < chapters.get(i).size();
		 * j++) { for (int k = 0; k < chapters.get(i).get(j).size(); k++) { p =
		 * sh.addWord(i, chapters.get(i).getName(), j,
		 * chapters.get(i).get(j).getName(),
		 * chapters.get(i).get(j).get(k).getWord1(),
		 * chapters.get(i).get(j).get(k).getWord2());
		 * System.out.println("woord toegevoegd " + k); } } }
		 * 
		 * 
		 * 
		 * sh.setTransactionSuccessful(); sh.endTransaction();
		 * 
		 * }
		 */
		/*
		setContentView(R.layout.chapters_grid);

		gridView = (GridView) findViewById(R.id.gridViewChapter);
		//adapter = new ChapterAdapter(this, test);
		adapter = new ChapterAdapter(this, chapters.getNames());

		gridView.setAdapter(adapter);

		gridView.setDrawSelectorOnTop(true);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				onListItemClick(position);
			}
		});
		*/
        setContentView(R.layout.simple_tabs);
        
        mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

        mPager = (ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        
        
        mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
        
        mIndicator.setViewPager(mPager);
		
		
	}
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Used to put dark icons on light action bar

        menu.add("Rate app").setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

        return true;
    }

	   @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        //This uses the imported MenuItem from ActionBarSherlock
	        //Toast.makeText(this, "Got click: " + item.toString(), Toast.LENGTH_SHORT).show();
	        if(item.getTitle()=="Rate app"){
	        	AppRater.showRateDialog(this);
	        }
	        return true;
	    }

	private void LoadPreferences() {
		SharedPreferences sharedPreferences = getSharedPreferences("test", 0);
		// Toast.makeText(this, sharedPreferences.getString("MEM2", ""),
		// 4000).show();
	}

	private void SavePreferences(String key, String value) {
		SharedPreferences sharedPreferences = getSharedPreferences("test", 0);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString(key, value);
		editor.commit();
	}

	private void readXML() {
		try {
			
			if(Locale.getDefault().getLanguage().equals("nl")){
				xpp = getResources().getXml(R.xml.data_nl);	
			} else{
				xpp = getResources().getXml(R.xml.data);
			}
			
			while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
				if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("CHAPTER")) {
					chapters.addChapter(readChapter());
				}

				xpp.next();
			}
		} catch (Throwable t) {
			Toast.makeText(this, "Request failed: " + t.toString(), 4000).show();
		}
	}

	private Chapter readChapter() throws XmlPullParserException, IOException {
		chapter = new Chapter();
		while (!(xpp.getEventType() == XmlPullParser.END_TAG && xpp.getName().equals("CHAPTER"))) {
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("CHAPTER_NAME")) {
				xpp.next();
				chapter.setName(xpp.getText());
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("SECTION")) {
				chapter.addSection(readSection());
			}
			xpp.next();
		}
		return chapter;
	}

	private Section readSection() throws XmlPullParserException, IOException {
		section = new Section();
		while (!(xpp.getEventType() == XmlPullParser.END_TAG && xpp.getName().equals("SECTION"))) {
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("SECTION_NAME")) {
				xpp.next();
				section.setName(xpp.getText());
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("WORD")) {
				section.addWord(readWord());
			}
			xpp.next();
		}
		return section;
	}

	private Word readWord() throws XmlPullParserException, IOException {
		word = new Word();
		while (!(xpp.getEventType() == XmlPullParser.END_TAG && xpp.getName().equals("WORD"))) {
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("W1")) {
				xpp.next();
				
				String tmp = xpp.getText();
				
				tmp = tmp.trim();
				
				word.setWord1(tmp);
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("W2")) {
				xpp.next();
				String tmp = xpp.getText();
				
				tmp = tmp.trim();
				
				word.setWord2(tmp);
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("TAGS")) {
				xpp.next();
				word.addTags(xpp.getText());
			}
			xpp.next();
		}
		return word;
	}
	
	public void clickTraining(View view) {
		Intent intent = new Intent(this, ChaptersViewActivity.class);
		intent.putExtra("chapters", chapters);
		startActivity(intent);
	}

	public void clickButton2(View view) {
		Toast.makeText(this, "TODO1", 4000).show();
		SavePreferences("MEM2", "test");
	}

	public void clickButton3(View view) {
		Toast.makeText(this, "TODO", 4000).show();
		SavePreferences("MEM2", "test2");
	}

	public void clickButton4(View view) {
		Toast.makeText(this, "TODO", 4000).show();
	}

	public void clickButton5(View view) {
		Toast.makeText(this, "TODO", 4000).show();
	}

	/*
	 public boolean onCreateOptionsMenu(Menu menu) {
		 MenuInflater inflater = getMenuInflater();
		 inflater.inflate(R.menu.test, menu);
		 return true;
	 }
	 */

	public void onListItemClick(int position) {
		Intent intent = new Intent(this, ChapterViewActivity.class);
		intent.putExtra("chapters", chapters);
		intent.putExtra("chapter", position);
		startActivity(intent);
	}

	/*
	 * optioneel inlezen via csv.. wat is makkelijker?
	 */
	private void readCSV() {

		try {
			CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));

			for (;;) {
				next = reader.readNext();
				if (next != null) {
					list.add(next);
				} else {
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class ChapterAdapter extends BaseAdapter {
		private Context context;
		private ArrayList<String> chapterNames;

		public ChapterAdapter(Context context, ArrayList<String> chapterNames) {
			this.context = context;
			this.chapterNames = chapterNames;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View gridItem;
			gridItem = new View(context);
			gridItem = inflater.inflate(R.layout.chapter, null);
			TextView textView = (TextView) gridItem.findViewById(R.id.chapter_name);
			AspectRatioImageView imageView = (AspectRatioImageView) gridItem.findViewById(R.id.myImageView);
			try{
				String uri = "drawable/c"+(position+1);
				
				int imageResource = getResources().getIdentifier(uri, null, getPackageName());
				Drawable image = getResources().getDrawable(imageResource);
				imageView.setImageDrawable(image);
			} catch(Exception ex){
				String uri = "chapter";
				int imageResource = getResources().getIdentifier(uri, null, getPackageName());
				Drawable image = getResources().getDrawable(imageResource);
				imageView.setImageDrawable(image);
			}
			
			textView.setText(chapterNames.get(position));
			return gridItem;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return chapterNames.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

	}
	
	class TestFragmentAdapter extends FragmentPagerAdapter {	    
	    private int mCount = chapters.getNames().size();

	    public TestFragmentAdapter(FragmentManager fm) {
	        super(fm);
	    }

	    @Override
	    public Fragment getItem(int position) {
	    	Bundle data = new Bundle();
	    	data.putSerializable("chapter", chapters.get(position));
	    	data.putInt("position", position);
	    	Fragment fragment = new GridViewFragment();
	    	fragment.setArguments(data);
	    	
	    	return fragment;
	    }

	    @Override
	    public int getCount() {
	        return mCount;
	    }
	    
	    @Override
	    public CharSequence getPageTitle(int position) {
	    	//return CONTENT[position];
	    	return chapters.getNames().get(position).toUpperCase();
	    }
	}
	


}